// axios 二次封装
import axios from 'axios'
import store from '@/store'

const service = axios.create({
    baseURL: '/api',
    timeout: 5000
})

service.interceptors.request.use(config => {
    console.log('发送请求:', config.method?.toUpperCase(), config.url, config.data || config.params);
    
    // 从store中获取token并添加到请求头
    const token = store.state.user.userinfo.token;
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
});

service.interceptors.response.use(res => {
    console.log('收到响应:', res);
    return res.data;
}, err => {
    console.error('请求出错:', err);
    return Promise.reject(err);
})

// 添加常用请求方法
service.get = (url, params) => {
    return service({
        method: 'get',
        url,
        params
    })
}

service.post = (url, data, config = {}) => {
    return service({
        method: 'post',
        url,
        data,
        ...config
    })
}

export default service